'use strict';
const uniID = require('uni-id-common');
const db = uniCloud.database();

exports.main = async (event, context) => {
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	
    const { uniIdToken, testId, limit } = body; 
    
	const uniIDIns = uniID.createInstance({ context });
	const {uid} = await uniIDIns.checkToken(uniIdToken);
	   if (!uid) {
	       return { code: 403, msg: "身份验证失败" };
	   }
    if (!testId) {
        return {
            code: 1, 
            message: '缺少 testId 参数'
        };
    }
	if(testId>3 || testId<1){
		return {
		    code: 2, 
		    message: '无效 testId 参数'
		};
	}
    
    try {
        const collection = db.collection('mind_test_results');
        let query = collection.where({ testId, user_id:uid }); // 增加 uid 作为查询条件
        
        // 如果 limit 存在，则限制查询数量
        if (limit && limit > 0) {
            query = query.limit(limit); // 动态设置 limit
        }
        
        const res = await query.get(); // 执行查询
        
        return {
            code: 0,
            message: '获取成功',
            data: res.data
        };
    } catch (error) {
        return {
            code: 2,
            message: '数据库查询失败',
            error: error.message
        };
    }
};